﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.ReportSource;

using System.Data;
using MvcPaging;

using Webs.Models;
using Libs.Data;

namespace Webs.Controllers
{
    public class BillController : Controller
    {
        //
        // GET: /Bill/

        
        public ActionResult Index()
        {
            return RedirectToAction("Add", "Bill");
        }

        [HttpGet]
        public ActionResult Add()
        {
            ViewBag.Title = SharedRes.SharedString.Add;
            return View();
        }

        [HttpPost]
        public ActionResult Add(BillModel model)
        {
            int id = 0;
            try
            {
                id = Save(model, DBMode.INSERT);
            }
            catch  (Exception ex) {
                ViewBag.ErrMsg = ex.Message;
                return View();
            }
            Session[Global.SESSION_MESSAGE] = SharedRes.SharedString.SavedSucc;
            return RedirectToAction("Edit", "Bill", new { id = id });
        }

        [HttpGet]
        public ActionResult Edit(int ?id)
        {
            if (!id.HasValue)
                return RedirectToAction("Add", "Bill");

            if (Session[Global.SESSION_MESSAGE] != null && Session[Global.SESSION_MESSAGE] != "")
            {
                ViewBag.SuccMsg = Session[Global.SESSION_MESSAGE];
                Session[Global.SESSION_MESSAGE] = "";
            }
            BillModel model = new BillModel();
            try
            {
                DBDataContext db = new DBDataContext();
                

                //Info
                Get_BillResult result = db.Get_Bill(id).SingleOrDefault<Get_BillResult>();

                if (result == null)
                {
                    ViewBag.ErrMsg = String.Format(SharedRes.SharedString.BillNotExists, id);
                    return View("Error");
                }

                model.BillNo = result.BillNo;
                model.Shipper = result.Shipper;
                model.Consignee = result.Consignee;
                model.BookingNo = result.BookingNo;
                model.BillOfLoadingNo = result.BillOfLoadingNo;

                model.DeliveryAgent = result.DeliveryAgent;
                model.NotifyParty = result.NotifyParty;
                model.PreCarriageBy = result.PreCarriageBy;
                model.PlaceOfReceipt = result.PlaceOfReceipt;
                model.OceanVessel = result.OceanVessel;
                model.PortOfLoading = result.PortOfLoading;

                model.PortOfDischarge = result.PortOfDischarge;
                model.PlaceOfDelivery = result.PlaceOfDelivery;
                model.FinalDestination = result.FinalDestination;
                model.TypeOfMovement = result.TypeOfMovement;

                model.FreightAndCharge = result.FreightAndCharge;
                model.ServiceContractNo = result.ServiceContractNo;
                model.NumberOfOriginal = result.NumberOfOriginal;
                model.CommodityCode = result.CommodityCode;
                model.ExchangeRate = result.ExchangeRate;
                model.DateLadenOnBoard = result.DateLadenOnBoard;
                model.PlaceDateOfIssue = result.PlaceDateOfIssue;
            }
            catch (Exception ex)
            {
                ViewBag.ErrMsg = ex.Message;
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(BillModel model)
        {            
            try
            {
                Save(model, DBMode.UPDATE);
            }
            catch (Exception ex)
            {
                ViewBag.ErrMsg = ex.Message;
                return View();
            }
            Session[Global.SESSION_MESSAGE] = SharedRes.SharedString.SavedSucc;
            //return RedirectToAction("Edit", "Bill", new { id = id });
            return View(model);
        }

        public ActionResult Clone(int id)
        {
            BillModel model = new BillModel();
            DBDataContext db = new DBDataContext();
            
            try
            {
                Get_BillResult result = db.Get_Bill(Convert.ToInt32(id)).SingleOrDefault<Get_BillResult>();

                if (result == null)
                {
                    ViewBag.ErrMsg = String.Format(SharedRes.SharedString.BillNotExists, id);
                    return View("Error");
                }

                model.BillNo = result.BillNo;
                model.Shipper = result.Shipper;
                model.Consignee = result.Consignee;
                model.BookingNo = result.BookingNo;
                model.BillOfLoadingNo = result.BillOfLoadingNo;
                ViewBag.Title = SharedRes.SharedString.Clone + " from: " + model.BillOfLoadingNo;

                model.DeliveryAgent = result.DeliveryAgent;
                model.NotifyParty = result.NotifyParty;
                model.PreCarriageBy = result.PreCarriageBy;
                model.PlaceOfReceipt = result.PlaceOfReceipt;
                model.OceanVessel = result.OceanVessel;
                model.PortOfLoading = result.PortOfLoading;

                model.PortOfDischarge = result.PortOfDischarge;
                model.PlaceOfDelivery = result.PlaceOfDelivery;
                model.FinalDestination = result.FinalDestination;
                model.TypeOfMovement = result.TypeOfMovement;

                model.FreightAndCharge = result.FreightAndCharge;
                model.ServiceContractNo = result.ServiceContractNo;
                model.NumberOfOriginal = result.NumberOfOriginal;
                model.CommodityCode = result.CommodityCode;
                model.ExchangeRate = result.ExchangeRate;
                model.DateLadenOnBoard = result.DateLadenOnBoard;
                model.PlaceDateOfIssue = result.PlaceDateOfIssue;

            }
            catch { }
            return View("Add", model);
        }

        private int Save(BillModel model, int mode)
        {
            DBDataContext db = new DBDataContext();                        

            Insert_Update_BillResult result =
                db.Insert_Update_Bill(model.BillNo, model.Shipper, model.Consignee, model.BookingNo, model.BillOfLoadingNo, model.DeliveryAgent,
                    model.NotifyParty, model.PreCarriageBy, model.PlaceOfReceipt, model.OceanVessel, model.PortOfLoading,
                    model.PortOfDischarge, model.PlaceOfDelivery, model.FinalDestination, model.TypeOfMovement, model.FreightAndCharge,
                    model.ServiceContractNo, model.NumberOfOriginal, model.CommodityCode, model.ExchangeRate, model.DateLadenOnBoard,
                    model.PlaceDateOfIssue, mode).SingleOrDefault<Insert_Update_BillResult>();

            return Convert.ToInt32(result.BillNo);
        }

        public ActionResult Delete(int? id)
        {
            if (!id.HasValue)
                return RedirectToAction("Add", "Bill");

            BillModel model = new BillModel();

            model.BillNo = Convert.ToInt32(id);
            Save(model, DBMode.DELETE);
            return RedirectToAction("Add", "Bill");
        }

        #region Bill Detail
        public ActionResult BillDetail(int id)
        {
            try
            {
                DBDataContext db = new DBDataContext();

                List<Get_BillDetailResult> lst = db.Get_BillDetail(id, 0).ToList<Get_BillDetailResult>();

                ViewBag.BillDetail = lst;
                ViewBag.BillNo = id;
            }
            catch (Exception ex)
            {
                ViewBag.ErrMsg = ex.Message;
            }
            return PartialView("_BillDetail");
        }

        [HttpGet]
        public ActionResult AddDetail(int ?id)
        {
            if (!id.HasValue)
                return RedirectToAction("Add", "Bill");

            DBDataContext db = new DBDataContext();
            BillDetailModel model = new BillDetailModel();
            Get_BillResult result = db.Get_Bill(id).SingleOrDefault<Get_BillResult>();

            model.BillNo = Convert.ToInt32(id);
            model.Container = "CONTAINER / SEAL NO:";
            model.Description = result.TypeOfMovement + "\r\n\r\nSHIPPER'S LOAD, STOW, COUNT AND SEAL";
            return View(model);
        }

        [HttpPost]
        public ActionResult AddDetail(BillDetailModel model)
        { 
            try
            {
                SaveDetail(model, DBMode.INSERT);
            }
            catch (Exception ex)
            {
                ViewBag.ErrMsg = ex.Message;
                return View();
            }
            Session[Global.SESSION_MESSAGE] = SharedRes.SharedString.SavedSucc;
            return RedirectToAction("Edit", "Bill", new { id = model.BillNo });                      
        }

        [HttpGet]
        public ActionResult EditDetail(int? id, int ?detail)
        {
            if (!id.HasValue)
                return RedirectToAction("Add", "Bill");

            if (!detail.HasValue)
                return RedirectToAction("Edit", "Bill", new { id = id });

            BillDetailModel model = new BillDetailModel();
            try
            {
                DBDataContext db = new DBDataContext();

                Get_BillDetailResult result = db.Get_BillDetail(id, detail).SingleOrDefault<Get_BillDetailResult>();

                if (result != null)
                {
                    model.BillDetailNo = result.BillDetailNo;
                    model.BillNo = result.BillNo;
                    model.Container = result.Container;
                    model.Description = result.Description;
                    model.GrossWeight = result.GrossWeight;
                }
            }
            catch (Exception ex)
            {
                ViewBag.ErrMsg = ex.Message;
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult EditDetail(BillDetailModel model)
        {                        
            try
            {
                DBDataContext db = new DBDataContext();

                SaveDetail(model, DBMode.UPDATE);
            }
            catch (Exception ex)
            {
                ViewBag.ErrMsg = ex.Message;
                return View(model);
            }            
            Session[Global.SESSION_MESSAGE] = SharedRes.SharedString.SavedSucc;
            return RedirectToAction("Edit", "Bill", new { id = model.BillNo });            
        }

        public ActionResult DeleteDetail(int ?id, int ?detail)
        {
            try
            {
                DBDataContext db = new DBDataContext();
                BillDetailModel model = new BillDetailModel();

                model.BillNo = Convert.ToInt32(id);
                model.BillDetailNo = Convert.ToInt32(detail);
                SaveDetail(model, DBMode.DELETE);
            }
            catch (Exception ex)
            {
                ViewBag.ErrMsg = ex.Message;
                return RedirectToAction("Edit", "Bill", new { id = id });
            }
            Session[Global.SESSION_MESSAGE] = SharedRes.SharedString.DeleteSucc;
            return RedirectToAction("Edit", "Bill", new { id = id });
        }

        private int SaveDetail(BillDetailModel model, int mode)
        {
            DBDataContext db = new DBDataContext();
            
            Insert_Update_BillDetailResult result =
                db.Insert_Update_BillDetail(model.BillNo, model.BillDetailNo, model.Container, model.Description, 
                model.GrossWeight, "", mode).SingleOrDefault<Insert_Update_BillDetailResult>();

            return Convert.ToInt32(result.BillDetailNo);
        }

        #endregion

        #region
        [HttpGet]
        public ActionResult Search()
        {
            SearchBillModel model = new SearchBillModel();

            DateTime dt = DateTime.Now;
            dt = new DateTime(dt.Year, dt.Month, 1);
            model.FrDate = dt.ToString("dd/MM/yyyy");
            model.ToDate = dt.AddMonths(1).AddDays(-1).ToString("dd/MM/yyyy");
            model.BookingNo = model.BillOfLoadingNo = "";
            return View(model);
        }

        [HttpPost]
        public ActionResult Search(SearchBillModel model)
        {            
            try
            {
                DBDataContext db = new DBDataContext();

                model.FrDate = (model.FrDate != null ? model.FrDate : "");
                if (model.FrDate != "" || model.FrDate != null)
                    model.FrDate = Global.ToYYYYMMDD(model.FrDate);
                else
                {
                    ViewBag.ErrMsg = @SharedRes.SharedString.ErrFromDate;
                    return View();
                }

                model.ToDate = (model.ToDate != null ? model.ToDate : "");
                if (model.ToDate != "" || model.ToDate != null)
                    model.ToDate = Global.ToYYYYMMDD(model.ToDate);
                else
                {
                    ViewBag.ErrMsg = @SharedRes.SharedString.ErrToDate;
                    return View();
                }
               
                List<Search_BillResult> lst = db.Search_Bill(model.FrDate, model.ToDate, "", "", model.BookingNo, model.BillOfLoadingNo).ToList<Search_BillResult>();
                ViewBag.Search = lst;
            }
            catch (Exception ex)
            {
                ViewBag.ErrMsg = ex.Message;
            }
            return View();
        }

        
        #endregion
        public void Print(int ?id, bool ?layout)
        {            
            DBService db = new DBService(Global.CONNECTION_STRING);
            
            layout = (layout.HasValue ? layout : true);
            using (ReportClass rpt = new ReportClass())
            {
                if (Convert.ToBoolean(layout))
                    rpt.FileName = Server.MapPath("~/") + "Reports//Bill.rpt";
                else
                    rpt.FileName = Server.MapPath("~/") + "Reports//BillNoLayout.rpt";
                rpt.Load();
                if (id.HasValue)
                {
                    DataTable dt = db.ExeSP_DataTable("Get_Bill", new string[] {"@BillNo"},
                        new object[] {id}, CommandType.StoredProcedure);

                    DataTable dtDetail = db.ExeSP_DataTable("Get_BillDetail", new string[] { "@BillNo" },
                        new object[] { id }, CommandType.StoredProcedure);

                    rpt.Database.Tables[0].SetDataSource(dt);
                    rpt.Subreports[0].Database.Tables[0].SetDataSource(dtDetail);
                }

                
                
                rpt.ExportToHttpResponse(ExportFormatType.PortableDocFormat, System.Web.HttpContext.Current.Response, false, "crReport");
            }
            
        }

        public ActionResult Dashboard()
        {
            return View();
        }
    }
}
